const express = require("express")
const router = express.Router()
const historicalDB = require("../../../db/historical")

// 获取文章详情
router.get("/getInfo", async (req, res) => {
  try {
    let { _id } = req.query
    // 查询是否有此文章
    let doc = null
    let prev = null
    let next = null

    doc = await historicalDB.findById(_id)
    if (!doc) {
      return res.send({
        code: 17,
        mes: "您要查找的文章不存在或已被删除"
      })
    }
    // 添加文章浏览量
    await historicalDB.findByIdAndUpdate(_id, {
      $inc: {
        vistor: 1
      }
    })
    // 查询上一篇文章
    prev = await historicalDB.findOne({
      date: { $gt: doc.date }
    }, {}, {
      sort: { date: -1 }
    })
    next = await historicalDB.findOne({
      date: { $lt: doc.date }
    }, {}, {
      sort: { date: -1 }
    })

    if (!prev) {
      return res.send({
        code: 0,
        mes: "文章详情",
        data: doc,
        next: {
          title: next?.name,
          _id: next?._id
        }
      })
    }
    if (!next) {
      return res.send({
        code: 0,
        mes: "文章详情",
        data: doc,
        prev: {
          title: prev?.name,
          _id: prev?._id
        }
      })
    }
    res.send({
      code: 0,
      mes: "文章详情",
      data: doc,
      prev: {
        title: prev?.name,
        _id: prev?._id
      },
      next: {
        title: next?.name,
        _id: next?._id
      }
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})

module.exports = router